
import ci from 'commander';
import * as shell from 'shelljs';
import { Config, ConfigWrapper } from './Config';
import pkg, { Package } from './pkg';
import path from 'path';

ci.version('0.1.0')
ci.usage('[options] <params ...>');

ci.option('-cfg, --config [value]', '指定配置文件', '.mvn-ci.config.js');

(async () => {




  let config: ConfigWrapper | null = null;

  try {

    // const cfgPath = path.join(shell.pwd().toString(),ci.config);
    const cfgPath = ci.config;

    // @ts-ignore
    const cfg = await import('../mvn-ci.config.js')

      config = new ConfigWrapper(cfg);

  } catch (e) {
    console.error(e);
  }

  console.log(config);

  if (!config && !/(init|--help|-h)/.test(process.argv.join(''))) {
    console.error(`找不到配置文件 ${ci.config}`);
  }

  ci.command('clean [projects...]')
    .description('清除指定子工程,没有参数清除所用')
    .action(projects => {
      if (!config) {
        console.error('配置错误');
        shell.exit(1);
        return;
      }
      console.log('开始清除工程');
      if (!projects || projects.length == 0) {
        shell.rm('-rf', config.outDir + '/*');
      } else {
        for (var ph of projects) {
          shell.rm('-rf', config.outDir + '/' + ph + '*');
        }
      }
    });

  ci.command('package [projects...]')
    .description('打包指定子工程,没有参数打包所有')
    .option('-e, --env [value]', '指定环境 (test,prod)')
    .option('-c, --compress [value]', '是否压缩文件', 'true')
    .action((projects: Package.Projects, opt: Package.Option) => {
      if (!config) {
        console.error('配置错误');
        shell.exit(1);
        return;
      }
      pkg(projects, opt, config);
    });

  ci.parse(process.argv);
})();